/*
 * I2C.c
 *
 * Created: 6/10/2013 8:53:27 PM
 *  Author: Crossfire
 */ 

#include "I2C.h"

void parse_data_crossroad()
{
	unsigned char data = 0;
	unsigned char save = 0;
	int shift = 6;
	int amount_read = 0;
	TWI_match_read_slave();
	amount_read++;
	_mode = (TWI_read_slave() & 1);
	PORTB = _mode; //debug
	PORTB = ~0; //debug
	TWI_match_read_slave();
	data = TWI_read_slave();
	amount_read++;
	//
	for(int i = 0; i < 37; i++)
	{
		for (int j = 0; j < 6; j++)
		{
			save = ((data >> shift) & 3);
			_crossroad[i][j] = save;
			shift -=2;
			if(shift == -2)
			{
				shift = 6;
				TWI_match_read_slave();
				data = TWI_read_slave();
				amount_read++;
				PORTB = amount_read; //debug
				_delay_ms(2);
			}
		}
	}
	while(amount_read < 57)
	{
		TWI_match_read_slave();
		TWI_read_slave();
		amount_read++;
		PORTB = amount_read; //debug
	}
	PORTB = 1; //debug
	_delay_ms(500);
}

// Function to initilaize slave
void TWI_init_slave(void)
{
	// Fill slave address to TWAR
	TWAR=CROSSROAD;
}

unsigned char TWI_read_slave(void)
{
	// Clear TWI interrupt flag,Get acknowlegement, Enable TWI
	TWCR= (1<<TWINT)|(1<<TWEA)|(1<<TWEN);
	// Wait for TWINT flag
	while (!(TWCR & (1<<TWINT)));
	// Wait for acknowledgement
	while((TWSR & 0xF8)!=0x80);
	// Get value from TWDR
	return TWDR;
	// send the receive value on PORTB
	//PORTB=recv_data;

}

//Function to match the slave address and slave dirction bit(read)
void TWI_match_read_slave(void)
{
	//Loop till correct acknoledgement have been received
	while((TWSR & 0xF8)!= 0x60)
	{
		//Get acknowlegement, Enable TWI, Clear TWI interrupt flag
		TWCR=(1<<TWEA)|(1<<TWEN)|(1<<TWINT);

		//Wait for TWINT flag
		while (!(TWCR & (1<<TWINT)));
	}
}